//
//  ResourceManager.h
//  TrackingSim
//
//  Created by Garrett Manka on 1/28/12.
//  Copyright (c) 2012. All rights reserved.
//

#ifndef TrackingSim_ResourceManager_h
#define TrackingSim_ResourceManager_h

#include <vector>
#include <string>



template< class T >
class ResourceManager
{
    typedef void (*loadFcnPtr)(const std::string& path, std::vector<T*>* resourceList);
    
private:
    
    ResourceManager();
    ~ResourceManager();
    
public:
    
    static void createRM( loadFcnPtr = NULL );
    
    static ResourceManager* getRM();
    
    void loadResource( const std::string& path );
    
    std::vector<T*>& getResourceList();
    
    T* getResourceByName( const std::string& name );
    
private:
    
    static ResourceManager* s_instance;
    static bool instance_created;
    
    static loadFcnPtr loader;
    
    std::vector<T*> m_resource_list;
};

template < class T >
ResourceManager<T>::ResourceManager()
{
    
}

template < class T >
ResourceManager<T>::~ResourceManager()
{
    for(int i = 0 ; i < m_resource_list ; ++i )
    {
        delete m_resource_list[i];
    }
    
    delete s_instance;
    s_instance = NULL;
    instance_created = false;
}

template < class T >
ResourceManager<T>* ResourceManager<T>::s_instance = NULL;

template < class T >
bool ResourceManager<T>::instance_created = false;

template < class T >
typename ResourceManager<T>::loadFcnPtr ResourceManager<T>::loader = NULL;

template < class T >
void ResourceManager<T>::createRM( loadFcnPtr loadFunction)
{
    if(!instance_created)
    {
        s_instance = new ResourceManager();
        loader = loadFunction;
        instance_created = true;
    }
}

template < class T >
ResourceManager<T>* ResourceManager<T>::getRM()
{
    return s_instance;
}

template < class T >
void ResourceManager<T>::loadResource( const std::string& path )
{
    if( loader != NULL )
    {
        loader(path, &m_resource_list);
    }
}

template <class T >
std::vector<T*>& ResourceManager<T>::getResourceList()
{
    return m_resource_list;
}

template < class T >
T* ResourceManager<T>::getResourceByName(const std::string& name)
{
    for(unsigned int i = 0 ; i < m_resource_list.size() ; ++i )
    {
        if( m_resource_list[i]->getName() == name )
        {
            return m_resource_list[i];
        }
    }
    
    return NULL;
}

#endif
